package research.model;

import java.util.List;

import org.eclipse.jface.viewers.AbstractListViewer;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;

import research.entity.Entity;
import research.persistence.IPersistenceListener;
import research.persistence.IPersistenceManager;

public class EntityListContentProvider implements IStructuredContentProvider, IPersistenceListener {
	
	private IHierarchyProvider hierarchy;
	private AbstractListViewer viewer;
	private IPersistenceManager datasource;
	private boolean hasNull;

	public EntityListContentProvider(IHierarchyProvider hierarchy, boolean hasNull) {
		super();
		this.hierarchy = hierarchy;
		this.hasNull = hasNull;
	}

	@Override
	public Object[] getElements(Object inputElement) {
		List<Entity> res = this.datasource.getDataSource().getAll(hierarchy.getRootType());
		if (hasNull)
			res.add(Entity.NULL_ENTITY);
		return res.toArray();
	}

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		this.viewer = (AbstractListViewer) viewer;
		this.datasource = (IPersistenceManager) newInput;
		
		IPersistenceManager oldManager = (IPersistenceManager) oldInput;
		IPersistenceManager newManager = (IPersistenceManager) newInput;
					
		if (oldManager != null)
			oldManager.removeListener(this);
		
		if (newManager != null)
			newManager.addListener(this);
	}

	@Override
	public void add(Entity entity) {
		if (hierarchy.supportsType(entity.getType()) && viewer != null) {
			viewer.add(entity);
		}
	}

	@Override
	public void remove(Entity entity) {
		if (hierarchy.supportsType(entity.getType()) && viewer != null) {
			viewer.remove(entity);
		}
	}

	@Override
	public void update(Entity entity) {
		if (hierarchy.supportsType(entity.getType()) && viewer != null) {
			viewer.update(entity, null);
		}
	}

}
